<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item v-if="formType === 'create'" label="资源类型" prop="kind">
        <el-radio-group v-model="formData.kind">
          <el-radio-button
            v-for="dict in SYSTEM_MENU_TYPE_OPTIONS"
            :key="dict.label"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="资源名称" prop="name">
        <el-input v-model="formData.name" clearable placeholder="请输入资源名称" />
      </el-form-item>
      <el-form-item label="上级菜单">
        <el-tree-select
          v-model="formData.parentId"
          :data="menuTree"
          :default-expanded-keys="[0]"
          :props="defaultProps"
          check-strictly
          node-key="id"
        />
      </el-form-item>
      <el-form-item label="资源代码" prop="code">
        <template #label>
          <Tooltip
            message="Controller 方法上的权限字符，如：@PreAuthorize(`@ss.hasPermission('system:user:list')`)"
            title="资源代码"
          />
        </template>
        <el-input v-model="formData.code" clearable placeholder="请输入资源代码" />
      </el-form-item>
      <el-form-item v-if="formData.kind !== IResourceType.Action" label="组件地址" prop="path">
        <el-input v-model="formData.path" clearable placeholder="例如说：system/user/index" />
      </el-form-item>
      <el-form-item v-if="formData.kind !== IResourceType.Action" label="路由地址" prop="route">
        <template #label>
          <Tooltip
            message="访问的路由地址，如：`user`。如需外网地址时，则以 `http(s)://` 开头"
            title="路由地址"
          />
        </template>
        <el-input v-model="formData.route" clearable placeholder="请输入路由地址" />
      </el-form-item>
      <el-form-item v-if="formData.kind === IResourceType.Menu" label="菜单图标">
        <IconSelect v-model="formData.iconCss" clearable />
      </el-form-item>
      <el-form-item label="显示排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" clearable controls-position="right" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { IResourceType } from '@/utils/dict'
import * as MenuApi from '@/api/system/menu'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { defaultProps } from '@/utils/tree'
import { useUserStore } from '@/store/modules/user'
import { omit } from 'lodash-es'

defineOptions({ name: 'SystemMenuForm' })
type FormOpenType = 'create' | 'update'

const { wsCache } = useCache()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const userStore = useUserStore() // 用户信息

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref<FormOpenType>('create') // 表单的类型：create - 新增；update - 修改
let dataId: number | undefined = undefined
const formData = ref({
  kind: IResourceType.Menu,
  name: '',
  parentId: 0 as number | undefined,
  code: '',
  path: '',
  route: '',
  iconCss: '',
  sort: Number(undefined)
})
const formRules = reactive({
  name: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '菜单顺序不能为空', trigger: 'blur' }],
  route: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const SYSTEM_MENU_TYPE_OPTIONS = [
  { label: '菜单', value: IResourceType.Menu },
  { label: '页面', value: IResourceType.Page },
  { label: '功能', value: IResourceType.Action }
]

/** 打开弹窗 */
const open = async (type: FormOpenType, id?: number, kind?: IResourceType, parentId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (parentId) {
    formData.value.parentId = parentId
  }
  // 修改时，设置数据
  if (id) {
    dataId = id
    formLoading.value = true
    const getMethod =
      kind === IResourceType.Menu
        ? MenuApi.getMenu
        : kind === IResourceType.Page
          ? MenuApi.getPage
          : MenuApi.getOperation
    try {
      const res = await getMethod(id)
      formData.value = { ...res, kind }
    } finally {
      formLoading.value = false
    }
  }
  // 获得菜单列表
  await getTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formData.value.kind === IResourceType.Menu || formData.value.kind === IResourceType.Page) {
      if (!isExternal(formData.value.route)) {
        if (!formData.value.parentId && formData.value.route.charAt(0) !== '/') {
          message.error('路径必须以 / 开头')
          return
        } else if (formData.value.parentId && formData.value.route.charAt(0) === '/') {
          message.error('路径不能以 / 开头')
          return
        }
      }
    }
    const data = formData.value
    const createMethod =
      data.kind === IResourceType.Menu
        ? MenuApi.createMenu
        : data.kind === IResourceType.Page
          ? MenuApi.createPage
          : MenuApi.createOperation
    const updateMethod =
      data.kind === IResourceType.Menu
        ? MenuApi.updateMenu
        : data.kind === IResourceType.Page
          ? MenuApi.updatePage
          : MenuApi.updateOperation
    if (formType.value === 'create') {
      await createMethod(data)
      message.success(t('common.createSuccess'))
    } else {
      await updateMethod(dataId!, omit(data, 'kind'))
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
    // 清空，从而触发刷新
    wsCache.delete(CACHE_KEY.ROLE_ROUTERS)
  }
}

/** 获取下拉框[上级菜单]的数据  */
const menuTree = ref<Tree[]>([]) // 树形结构
const getTree = async () => {
  menuTree.value = []
  const res = await MenuApi.getMenuList(userStore.getUser.uid, {
    status: undefined,
    name: undefined
  })
  // let menu: Tree = { id: 0, name: '主类目', children: [] }
  // menu.children = handleTree(res)
  // menuTree.value.push(menu)
  // menuTree.value = handleTree(res)
  menuTree.value = res
}

/** 重置表单 */
const resetForm = () => {
  dataId = undefined
  formData.value = {
    kind: IResourceType.Menu,
    name: '',
    parentId: undefined,
    code: '',
    path: '',
    route: '',
    iconCss: '',
    sort: Number(undefined)
  }
  formRef.value?.resetFields()
}

/** 判断 path 是不是外部的 HTTP 等链接 */
const isExternal = (path: string) => {
  return /^(https?:|mailto:|tel:)/.test(path)
}
</script>
